<template>
  <div class="count">
    <button class="minus"
            @click="count(-1)">-</button>
    <input class="inp"
           :value="value"
           @change="handleChange"
           type="text">
    <button class="add"
            @click="count(+1)">+</button>
  </div>
</template>

<script>
export default {
  name: 'CountBox',
  // v-model 双向绑定的value
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  methods: {
    // 添加/删减处理
    count (num) {
      if (num === -1) {
        if (this.value <= 1) {
          return
        }
        // this.value是本组件的value
        this.$emit('input', this.value + num)
      }
      this.$emit('input', this.value + num)
    },

    // 处理input值
    handleChange (e) {
      let num = +e.target.value
      if (isNaN(num) || num < 0) {
        e.target.value = this.value
        return
      }


      /*  
      错误写法：不能直接修改父组件的值
      this.value = e.target.value */

      this.$emit('input', num)

    }
  }
}
</script>

<style lang="less">
.count {
  display: flex;
  button {
    width: 30px;
    height: 30px;
    border: none;
    background: #efefef;
  }
  .inp {
    width: 40px;
    border: none;
    outline: none;
    margin: 0 5px;
    background: #efefef;
    text-align: center;
  }
}
</style>